﻿using System;
using System.Collections.Generic;
using System.Web.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace EnvSafe.Site.RedirApp
{
    public class Global : System.Web.HttpApplication
    {
        const string Str_RedirectTarget = "RedirectTarget";
        static Dictionary<string, string> RedirectTargets = new Dictionary<string, string>();

        protected void Application_Start(object sender, EventArgs e)
        {
            var headers = WebConfigurationManager.AppSettings.AllKeys.Where(h => h.StartsWith($"{Str_RedirectTarget}:"));
            foreach (var h in headers)
            {
                RedirectTargets.Add(h.Substring(Str_RedirectTarget.Length + 1).ToLower(), WebConfigurationManager.AppSettings[h]);
            }

            if (WebConfigurationManager.AppSettings.AllKeys.Contains(Str_RedirectTarget))
            {
                RedirectTargets.Add("default", WebConfigurationManager.AppSettings[Str_RedirectTarget]);
            }
            else
            {
                RedirectTargets.Add("default", WebConfigurationManager.AppSettings[headers.First()]);
            }
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var requestkey = Request.Url.Host.ToLower();
            var target = string.Empty;
            if (RedirectTargets.ContainsKey(requestkey))
            {
                target = RedirectTargets[requestkey];
            }
            else
            {
                target = RedirectTargets["default"];
            }
            Response.Redirect($"{target}\\{Request.Url.PathAndQuery ?? ""}", true);
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}